package com.eascs.crm.loanstart.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.IdCard;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.vo.ModelResult;
import com.eascs.crm.loanstart.form.CustomerBasicInfoForm;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
@Service
public class LoanStartServiceImpl {
	private final Logger logger = LoggerFactory.getLogger(LoanStartServiceImpl.class);
	@Reference
	CustomerService customerService;
	public Map<String, String> saveOrupdateCustomerBasicInfo(CustomerBasicInfoForm cbiForm) {
		// 存放验证信息
		Map<String, String> map = new HashMap<>();
		String returnFlag = "success";
		map.put("returnFlag", returnFlag);

		// 客户基本信息
		CustomerEntity basicInfo = new CustomerEntity();

		// 后台验证
		// 1.验证客户身份证
		if (cbiForm != null && cbiForm.getIdType().equals("IDC")) {
			boolean flag1 = IdCard.isIDCard(cbiForm.getIdNumber());
			if (flag1 == false) {
				returnFlag = "客户身份证输入有误";
				map.put("returnFlag", returnFlag);
				return map;
			}
		}
		if(cbiForm.getMaritalStatus()==2){
		// 2.验证客户配偶身份证
		if (cbiForm != null && StringUtil.isNotBlank(cbiForm.getMate_idType())
				&& cbiForm.getMate_idType().equals("IDC")) {
			if (2 == cbiForm.getMaritalStatus()) {
				boolean flag2 = IdCard.isIDCard(cbiForm.getMate_idNumber());
				if (flag2 == false) {
					returnFlag = "客户配偶身份证输入有误";
					map.put("returnFlag", returnFlag);
					return map;
				}
				// 3.客户和配偶的证件不能一致
				if (cbiForm != null && cbiForm.getMate_idNumber().equals(cbiForm.getIdNumber())
						&& cbiForm.getIdType().equals("IDC")) {
					returnFlag = "客户和配偶的证件不能一致";
					map.put("returnFlag", returnFlag);
					return map;
				}
			}
		  }
		}
		// 客户标示信息：通过证件号码，证件类型，查出客户信息及其扩展信息是否存在，来确定后面是修改逻辑还是新增逻辑
		String hisCustomerId = cbiForm.getCustomerId();
		String hisMaleBasicId = cbiForm.getMateId();
		String customerId = null;
		String maleBasicId = null;
		customerId = customerService.isCustomerExists(cbiForm.getIdNumber(), cbiForm.getIdType());
		maleBasicId = customerService.isCustomerExists(cbiForm.getMate_idNumber(), cbiForm.getMate_idType());

		// 对比逻辑：确认客户是否属于重复添加
		int flag = compareIdCard(hisCustomerId, hisMaleBasicId, customerId, maleBasicId);
		if (flag == 1) {
			returnFlag = "客户证件号码已存在，不能重复添加";
			map.put("returnFlag", returnFlag);
			return map;
		}
		User user = UserHolder.getUser();
		// 客户信息
		if (StringUtil.isNotBlank(hisCustomerId)) {

			basicInfo = customerService.queryCustomerEntityByCustomerId(hisCustomerId);
			if(cbiForm.getMaritalStatus() != 2){
				basicInfo.setSpouse(null);
				basicInfo.setMateId(null);
			}
			if (user != null) {
				basicInfo.setModifier(user.getCname());
				basicInfo.setModifyId(user.getNo());
			}

		} else {
			if (user != null) {
				basicInfo.setCreator(user.getCname());
				basicInfo.setModifier(user.getCname());
				basicInfo.setCreateId(user.getNo());
				basicInfo.setModifyId(user.getNo());
			}
		}

		// 赋值客户信息
		basicInfo.setCustomerFamilyName(cbiForm.getCustomerFamilyName());
		basicInfo.setCustomerGivenName(cbiForm.getCustomerGivenName());
		basicInfo.setIdNumber(cbiForm.getIdNumber());
		basicInfo.setIdType(cbiForm.getIdType());
		basicInfo.setMaritalStatus(cbiForm.getMaritalStatus());
		basicInfo.setMobileNumber(cbiForm.getMobileNumber());
		basicInfo.setCustomerName(cbiForm.getCustomerFamilyName() + cbiForm.getCustomerGivenName());
		basicInfo.setLicenseExpirationDate(DateUtils.formateStandDate(cbiForm.getLicenseExpirationDate()));
		basicInfo.setCustomerNamePinyin(cbiForm.getSurnamePinyin()+cbiForm.getNamePinyin());
		basicInfo.setCustomerFamilyNamePy(cbiForm.getSurnamePinyin());
		basicInfo.setCustomerGivenNamePy(cbiForm.getNamePinyin());
		// 赋值给配偶信息
		if (cbiForm.getMaritalStatus() == 2) {
			basicInfo.setMateId(cbiForm.getMateId());
			CustomerEntity mate = new CustomerEntity();
			mate.setCustomerId(cbiForm.getMateId());
			mate.setCustomerFamilyName(cbiForm.getMate_customerFamilyName());
			mate.setCustomerGivenName(cbiForm.getMate_customerGivenName());
			mate.setIdNumber(cbiForm.getMate_idNumber());
			mate.setIdType(cbiForm.getMate_idType());
			mate.setMaritalStatus(cbiForm.getMaritalStatus());
			mate.setMobileNumber(cbiForm.getMate_mobileNumber());
			mate.setCustomerName(cbiForm.getMate_customerFamilyName() + cbiForm.getMate_customerGivenName());
			mate.setCustomerNamePinyin(cbiForm.getMate_surnamePinyin()+cbiForm.getMate_namePinyin());
			mate.setLicenseExpirationDate(DateUtils.formateStandDate(cbiForm.getMate_licenseExpirationDate()));
			mate.setMateId(cbiForm.getCustomerId());
			mate.setCustomerFamilyNamePy(cbiForm.getMate_surnamePinyin());
			mate.setCustomerGivenNamePy(cbiForm.getMate_namePinyin());
			if (StringUtil.isBlank(cbiForm.getMateId())) {
				if (user != null) {
					mate.setCreator(user.getCname());
					mate.setModifier(user.getCname());
					mate.setCreateId(user.getNo());
					mate.setModifyId(user.getNo());
				}
				mate.setCreateDate(new Date());
				mate.setModifyDate(new Date());
			} else {
				if (user != null) {
					mate.setModifier(user.getCname());
					mate.setModifyId(user.getNo());
				}
				mate.setModifyDate(new Date());

			}
			basicInfo.setSpouse(mate);
		}

		logger.info("basicInfo=={}", basicInfo.getCustomerFamilyNamePy());

		

		logger.info("名拼音={}", basicInfo.getCustomerFamilyNamePy());
		logger.info("姓拼音={}", basicInfo.getCustomerGivenNamePy());

		// 修改客户信息
		if (StringUtil.isBlank(hisCustomerId)) {
			basicInfo.setCreateDate(new Date());
			basicInfo.setModifyDate(new Date());
			ModelResult<CustomerEntity> model = customerService.addCustomer(basicInfo);
			logger.info("addCustomer=={},{}", model.isSuccess(),model.getErrMsg());
			if (model.isSuccess()) {
				hisCustomerId = model.getModel().getCustomerId();
			}
			
		} else {
			basicInfo.setModifyDate(new Date());
			ModelResult<CustomerEntity> model =customerService.updateCustomer(basicInfo);
			logger.info("updateCustomer=={},{}", model.isSuccess(),model.getErrMsg());
		}

		map.put("customerId", hisCustomerId);
		map.put("maleBasicId", maleBasicId);
		return map;
	}

	private int compareIdCard(String hisCustomerId, String hisMaleBasicId, String customerId, String maleBasicId) {
		// 新增客户信息的时候，客户证件号码重复
		if (StringUtil.isBlank(hisCustomerId) && StringUtil.isNotBlank(customerId)) {
			return 1;
		}
		// 新增客户信息的时候，配偶的证件号码重复
		if (StringUtil.isBlank(hisCustomerId) && StringUtil.isBlank(hisMaleBasicId)
				&& StringUtil.isNotBlank(maleBasicId)) {
			return 2;
		}
		// 修改客户信息的时候，客户证件号码改成了另一个已存在的号码
		if (StringUtil.isNotBlank(hisCustomerId) && StringUtil.isNotBlank(customerId)
				&& !hisCustomerId.equals(customerId)) {
			return 1;
		}
		// 修改客户信息的时候，配偶证件号码改成了另一个已存在的号码
		if (StringUtil.isNotBlank(hisMaleBasicId) && StringUtil.isNotBlank(maleBasicId)
				&& !hisMaleBasicId.equals(maleBasicId)) {
			return 2;
		}
		// 修改客户信息的时候，新增配偶信息=====（新增配偶的时候，新增一个未婚，已存在的客户认为是合法的）=====
		if (StringUtil.isNotBlank(hisCustomerId) && StringUtil.isBlank(hisMaleBasicId)
				&& StringUtil.isNotBlank(maleBasicId)) {
			CustomerEntity basicInfo = customerService.queryCustomerEntityByCustomerId(maleBasicId);
			if (basicInfo!=null) {
				if (basicInfo.getMaritalStatus() !=null &&  basicInfo.getMaritalStatus()== 2) {
					return 3;// 如果新增的配偶是已婚状态，就不能再添加
				}
			}
			return 0;
		}
		return 0;
	}

}
